#!/usr/bin/perl
use strict;
use DBI;
use HTTP::Date;
use Config::IniFiles;

require "/var/www/cgi-bin/gnugraph/rcoos/timeZone.lib";
require "/var/www/cgi-bin/gnugraph/rcoos/graphAll.lib";

#my $dbname="/var/www/html/RCOOS/website/latest.db";

#my $dbh = DBI->connect("dbi:SQLite:dbname=$dbname", "", "",
           #         { RaiseError => 1, AutoCommit => 1 });
#if(!defined $dbh) {die "Cannot connect to database!\n";}
 my $dbh=getdbConn();
 if($dbh==0){ die "Cannot connect to database!\n";}


 my $sql="select substr(platform_handle,1,4),substr(m_date,1,13),count(*) from multi_obs where age(m_date)<='3 days' group by substr(platform_handle,1,4),substr(m_date,1,13) order by substr(m_date,1,13),substr(platform_handle,1,4)";
 my $sth = $dbh->prepare($sql);
 $sth->execute();
 
 my $i=0;

 my $graph_data_file ="/var/www/html/images/".'gnuplot_'.int(rand(10000000));

 open (TEMPFILE,">$graph_data_file");
 my (@platform,@mdate,%cormp,%carocoops,%nerr,%nws,%ndbc,%nos,%seacoos);
 while (my @data = $sth->fetchrow_array) {
     if($data[0] eq "corm"){
         $cormp{$data[1]}=$data[2];
     }
     if($data[0] eq "caro"){
         $carocoops{$data[1]}=$data[2];
     }
     if($data[0] eq "nos."){
         $nos{$data[1]}=$data[2];
     }
     if($data[0] eq "nws."){
         $nws{$data[1]}=$data[2];
     }
     if($data[0] eq "ndbc"){
         $ndbc{$data[1]}=$data[2];
     }
     if($data[0] eq "seac"){
         $seacoos{$data[1]}=$data[2];
     }
     if($data[0] eq "nerr"){
         $nerr{$data[1]}=$data[2];
     }
     if(!(grep $_ eq $data[1],@mdate)){
        push(@mdate,$data[1]);
     }
     
 }

 for($i=0;$i<@mdate;$i++){
    print TEMPFILE "$mdate[$i]\t$cormp{$mdate[$i]}\t$carocoops{$mdate[$i]}\t$ndbc{$mdate[$i]}\t$nos{$mdate[$i]}\t$nerr{$mdate[$i]}\t$nws{$mdate[$i]}\t$seacoos{$mdate[$i]}\n";
     #print "$mdate[$i]\tcormp$cormp{$mdate[$i]}\tcarocoops$carocoops{$mdate[$i]}\tndbc$ndbc{$mdate[$i]}\tnos$nos{$mdate[$i]}\tnerr$nerr{$mdate[$i]}\tnws$nws{$mdate[$i]}\tseacoos$seacoos{$mdate[$i]}\n";
 }
 if(keys(%cormp)>0){
     push(@platform,"cormp");
 }
 if(keys(%carocoops)>0){
     push(@platform,"carocoops");
 }
 if(keys(%ndbc)>0){
    push(@platform,"ndbc");
 }
 if(keys(%nos)>0){
    push(@platform,"nos");
 }
 if(keys(%nerr)>0){
    push(@platform,"nerr");
 }
 if(keys(%nws)>0){
   push(@platform,"nws");
 }
 if(keys(%seacoos)>0){
   push(@platform,"seacoos");
 }
 
 close TEMPFILE ;

 if($i==0){
  
 }
 else {
    my $title="RCOOS Station reporting";
    my $units="Counts";

    my $imgname="/var/www/html/images/rcoosstats.png";
    
    graphStats($graph_data_file, $title, $units, $imgname,\@platform); 
    
 }



 $sth->finish();
 undef $sth;
 $dbh->disconnect();

 exit 0;

